package com.cy.rsspush.wx;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    public static String sendGet(String url, String query) throws Exception {
        String fullUrl = url + "?" + query;
        HttpURLConnection connection = (HttpURLConnection) new URL(fullUrl).openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");

        if (connection.getResponseCode()!= 200) {
            throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));

        StringBuilder sb = new StringBuilder();
        String output;
        while ((output = br.readLine())!= null) {
            sb.append(output);
        }
        connection.disconnect();
        return sb.toString();
    }


    public static String sendPost(String url, String data) throws Exception {
        URL fullUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) fullUrl.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        connection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(data);
        wr.flush();
        wr.close();

        if (connection.getResponseCode()!= 200) {
            throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));

        StringBuilder sb = new StringBuilder();
        String output;
        while ((output = br.readLine())!= null) {
            sb.append(output);
        }

        connection.disconnect();

        return sb.toString();
    }
}

